from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.forms.models import model_to_dict

from .models import Job, Resume
from interview.dingtalk import send

import json
import logging

logger = logging.getLogger(__name__)


# 使用annotation 来注册 信号处理器
@receiver(signal=post_save, sender=Resume, dispatch_uid='resume_post_save_dispatcher')
@receiver(signal=post_save, sender=Job, dispatch_uid='job_post_save_dispatcher')
def post_save_callback(sender, instance=None, created=False, **kwargs):
    message = ""
    if isinstance(instance, Job):
        message = f"Job for {instance.job_name} has been saved"
    else:
        message = f"Resume for {instance.username} {instance.apply_position} has been saved"

    logger.info(message)
    send(message)


def post_delete_callback(sender, instance=None, using=None, **kwargs):
    dict_obj = model_to_dict(instance, exclude=['picture', 'attachment', "created_date", "modified_date"])
    message = f'Instance of {type(instance)} has been deleted: {json.dumps(dict_obj, ensure_ascii=False)}'
    logger.info(message)
    send(message)


# 手工注册信号
post_delete.connect(post_delete_callback, sender=Resume, dispatch_uid='resume_post_delete_dispatcher')

